package ProjectManagement;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import com.spm.pojo.Teacher;

@WebServlet(name = "RegisterServlet",value="/ProjectManagement/RegisterServlet.do")
public class RegisterServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session=req.getSession();
        req.setCharacterEncoding("UTF-8");
        String username=req.getParameter("username").trim();
        String password=req.getParameter("password").trim();
        String Tname=req.getParameter("Tname").trim();
        String Tsex=req.getParameter("Tsex").trim();
        String imageValue=req.getParameter("imageValue");
        String sRand=(String) session.getAttribute("sRand");
        if((StringUtil.isEmpty(username)||StringUtil.isEmpty(password))&&imageValue.equals(sRand)){
            Teacher teacher=new Teacher(username,password,Tname,Tsex);
            TeacherDaoImpl usersdao=new TeacherDaoImpl();
            if (usersdao.isLogin(teacher)){
                req.setAttribute("error", "用户名已经存在！请重新输入");
                req.getRequestDispatcher("TeacherRegister.jsp").forward(req,resp);
                return;
            }else {
                usersdao.addTeacher(teacher);
                req.getRequestDispatcher("TeacherLogin.jsp").forward(req, resp);
                return;
            }
        }
        else if(StringUtil.isEmpty(imageValue)){
            req.setAttribute("error", "请输入验证码！");
            req.getRequestDispatcher("TeacherRegister.jsp").forward(req,resp);
            return;
        }else if(!imageValue.equals(sRand)){
            req.setAttribute("error", "验证码错误！");
            req.getRequestDispatcher("TeacherRegister.jsp").forward(req,resp);
            return;
        }

    }
}
